<?php


namespace App\Http\Controllers;


use App\Models\ApplicationForm;
use App\Models\ClassAndGradeTime;
use App\Models\Club;
use App\Models\School;
use App\Models\SchoolClassAndGrade;
use App\Models\StudentApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class QuestionnaireController extends Controller
{
    public function questionnaire(Request $request)
    {
        $formId = $request->get('form_id');

        if (empty($formId)) exit('<h1>数据有误</h1>');

        $formInfo = ApplicationForm::query()->findOrFail($formId);

        if ($formInfo->status === 0) {
            exit('<h1>报名已结束</h1>');
        }

        $schoolInfos = School::query()->whereIn('id', $formInfo->school_ids)->get()->toArray();

        $clubInfos = Club::query()->whereIn('id', $formInfo->club_ids)->get()->toArray();

        return view('mobile.questionnaire', [
            'school' => $schoolInfos,
            'club' => $clubInfos,
            'form_id' => $formId,
        ]);
    }

    public function get_load_classroom_select(Request $request)
    {
        $schoolId = $request->get('school_id');
        $clubId = $request->get('club_id');

        if (!$schoolId || !$clubId) {
            return response()->json(['status' => 1, 'data' => []]);
        }

        $classInfo = SchoolClassAndGrade::query()
            ->where('school_id', $schoolId)
            ->where('club_id', $clubId)
            ->where('status', 1)
            ->get()->toArray();

        return response()->json(['status' => 1, 'data' => $classInfo]);
    }

    public function get_load_time_select(Request $request)
    {
        $classId = $request->get('class_id');

        if (!$classId) {
            return response()->json(['status' => 1, 'data' => []]);
        }

        $timeInfo = ClassAndGradeTime::query()
            ->where('class_and_grade_id', $classId)
            ->get()->toArray();

        return response()->json(['status' => 1, 'data' => $timeInfo]);
    }

    protected function post_student_application_common_validate($input, $extRule = [], $extMsg = [])
    {
        $rule = [
            'club_id' => 'required|integer',
            'school_id' => 'required|integer',
            'class_id' => 'required|integer',
            'time_id' => 'required|integer',
            'name' => 'required',
            'phone' => 'required',
            'form_id' => 'required'
        ];

        $rule = array_merge($rule, $extRule);

        $msg = [
            'club_id.required' => '请选择社团',
            'school_id.required' => '请选择学校',
            'class_id.required' => '请选择班级',
            'time_id.required' => '请选择时间段',
            'name.required' => '请输入姓名',
            'phone.required' => '请输入手机号',
            'form_id.required' => 'DATA ERROR',
        ];

        $msg = array_merge($msg, $extMsg);

        Validator::make($input, $rule, $msg)->validate();
    }

    public function post_student_application(Request $request)
    {
        $input = $request->all(['club_id', 'school_id', 'class_id', 'time_id', 'name', 'phone', 'form_id','school_class_name']);

        $this->post_student_application_common_validate($input);

        $timeInfo = ClassAndGradeTime::query()->findOrFail($input['time_id']);

        // 判断班级--时间段内的人数是否已满
        // 查询报名人数
        $countKey = sprintf('%s_%s_%s_%s', $input['club_id'], $input['school_id'], $input['class_id'], $input['time_id']);
//        dd($countKey);
        $count = Redis::incr($countKey) - 1;

        if ($timeInfo->max_num <= $count) {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名人数已满，请选择别的时间段']);
        }

        $key = 'update_application_info_key_%s';

        $input['class_and_grade_id'] = $input['class_id'];

        try {
            $studentApplication = StudentApplication::query()->create($input);
        } catch (\Exception $e) {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名失败 40001']);
        }

        if ($studentApplication) {
            $key = sprintf($key, $studentApplication->id);
            $token = uniqid();
            Redis::set($key, $token);
            return response()->json(['status' => 1, 'data' => ['id' => $studentApplication->id, 'token' => $token]]);
        } else {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名失败']);
        }
    }

    public function post_update_student_application(Request $request)
    {
        $input = $request->all(['club_id', 'school_id', 'class_id', 'time_id', 'name', 'phone', 'form_id', 'id', 'token','school_class_name']);

        $rule = [
            'id' => 'required',
            'token' => 'required'
        ];

        $this->post_student_application_common_validate($input, $rule);

        $timeInfo = ClassAndGradeTime::query()->findOrFail($input['time_id']);

        $key = 'update_application_info_key_%s';

        $key = sprintf($key, $input['id']);

        $token = Redis::get($key);

        if ($token !== $input['token']) {
            return response()->json(['status' => 0, 'msg' => '报名失败 40002']);
        }

        $studentApplicationInfo = StudentApplication::query()->findOrFail($input['id']);

        $countKey = sprintf('%s_%s_%s_%s', $input['club_id'], $input['school_id'], $input['class_id'], $input['time_id']);
//        dd($countKey);
        $count = Redis::incr($countKey) - 1;

        if ($timeInfo->max_num <= $count) {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名人数已满']);
        }

        $input['class_and_grade_id'] = $input['class_id'];

        unset($input['class_id'],$input['token']);

        try {
            $res = StudentApplication::query()->where('id', $input['id'])->update($input);
        } catch (\Exception $e) {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名失败 '.$e->getMessage()]);
        }

        if ($res) {
            $changeKey = sprintf('%s_%s_%s_%s', $studentApplicationInfo->club_id, $studentApplicationInfo->school_id, $studentApplicationInfo->class_and_grade_id, $studentApplicationInfo->time_id);
            Redis::decr($changeKey);
            return response()->json(['status' => 1, 'data' => ['id' => $studentApplicationInfo->id, 'token' => $token]]);
        } else {
            Redis::decr($countKey);
            return response()->json(['status' => 0, 'msg' => '报名失败']);
        }
    }

    public function get_student_application_info(Request $request)
    {
        $id = $request->get('id');
        $token = $request->get('token');
        $key = 'update_application_info_key_%s';

        $key = sprintf($key, $id);

        $tokenV = Redis::get($key);

        if ($token !== $tokenV) {
            return response()->json(['status' => 0, 'msg' => '信息验证失败']);
        }

        $studentApplicationInfo = StudentApplication::query()->findOrFail($id);

        return response()->json(['status' => 1, 'data' => $studentApplicationInfo]);
    }
}
